const express = require('express');
const router = express.Router();
const {checkMobile} = require('../mysql/admin');
const parseRes = require('../tools/parseRes');
const sendSms = require('../sms/send');

router.get('/test', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/getCode', async function(req, res, next) {
  const mobile = req.param('mobile');
  const flag = await checkMobile(mobile);
  if (!flag) {
    res.send(parseRes.parseError(parseRes.ERROR_MOBILE_ERROR, parseRes.ERROR_MOBILE_ERROR_MSG));
    return;
  }
  let code = '';
  for (let i = 0; i < 4; i++) {
    code += Math.floor(Math.random() * 10);
  }
  const smsFlag = await sendSms(mobile, code);
  if (smsFlag !== -1) {
    req.session.captchaCode = code;
    req.session.userInfo = {
      captchaCode: code,
      mobile
    };
    res.send(parseRes.parseSuccess({}));
  } else {
    res.send(parseRes.parseError(parseRes.ERROR_SMS_ERROR, parseRes.ERROR_SMS_ERROR_MSG));
  }
});

router.post('/login', async function(req, res) {
  const {mobile, captchaCode} = req.body;
  const userInfo = req.session.userInfo;
  if (userInfo.mobile !== mobile || userInfo.captchaCode !== captchaCode) {
    res.send(parseRes.parseError(parseRes.ERROR_CAPTCHA_CODE, parseRes.ERROR_CAPTCHA_CODE_MSG));
    return;
  }
  req.session.userInfo.auth = true;
  res.send(parseRes.parseSuccess({mobile}));
});

router.get('/getUserInfo', async function(req, res) {
  const userInfo = req.session.userInfo;
  if (userInfo && userInfo.auth) {
    res.send(parseRes.parseSuccess({mobile: userInfo.mobile}));
    return;
  }
  res.send(parseRes.parseError(parseRes.ERROR_SESSIONID, parseRes.ERROR_SESSIONID_MSG));
});

module.exports = router;
